using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.WebTesting;

namespace WebAndLoadTestPlugins
{
    public class ExtractQueryString : ExtractionRule
    {
        string m_QueryStringParamName;
        public string QueryStringParamName
        {
            get { return m_QueryStringParamName; }
            set { m_QueryStringParamName = value; }
        }

        public override void Extract(object sender, ExtractionEventArgs e)
        {
            List<string> URLs = new List<string>();
            string URL;
            
            e.Success = false;
            if (!e.Response.IsHtml)
                return;

            // Find all tags with a query string parameter that matches
            foreach (HtmlTag tag in e.Response.HtmlDocument.GetFilteredHtmlTags("a"))
            {
                URL = tag.GetAttributeValueAsString("href");
                int queryStringIndex = URL.IndexOf('?');
                if ((queryStringIndex != -1) && URL.IndexOf(QueryStringParamName, queryStringIndex) != -1)
                {
                    URLs.Add(URL);
                }
            }

            if (URLs.Count == 0)
            {
                e.Success = false;
                return;
            }

            // Randomly pick a URL
            Random rand = new Random();
            URL = URLs[rand.Next(URLs.Count)];

            // Extract the query string
            int valueIndex = URL.IndexOf(QueryStringParamName);
            int startIndex = valueIndex + QueryStringParamName.Length + 1;
            int endIndex = URL.IndexOf("&", startIndex);
            if (endIndex == -1)
            {
                endIndex = URL.Length;
            }
            string value = URL.Substring(startIndex, endIndex - startIndex);
            e.WebTest.Context.Add(this.ContextParameterName, value);
            e.Success = true;
            return;
        }

        public override string RuleName
        {
            get { return "Extract Random Link"; }
        }
    }
}
